package com.oitsm.plugin.entity;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 采集器的输出
 * @author Arab Runner
 * Jul 17, 2011 10:43:43 AM
 */
public class Response {
	/**
	 * 是否采集成功
	 */
	private boolean success;
	/**
	 * 失败的描述
	 */
	private String failureDesc;
	
	/**
	 * 响应输出项
	 */
	private List<ResponseItem> items = new ArrayList<ResponseItem>();
	
	public void setFailure(String desc){
		this.success = false;
		this.failureDesc = desc;
	}
	
	public void setSuccess(boolean success){
		this.success = success;
	}
	
	public void clear(){
		success = false;
		failureDesc = null;
		items.clear();
	}
	
	public void add(String name,Object val,String unit){
		ResponseItem d = new ResponseItem();
		d.setValue(val);
		d.setUnit(unit);
		d.setName(name);
		items.add(d);
	}
	
	public JSONObject toJSON(){
		JSONObject jo = new JSONObject();
		jo.put("success", success);
		if(!success){
			jo.put("failureDesc", failureDesc);
		}
		
		JSONArray data = new JSONArray();
		for(ResponseItem d : items){
			JSONObject item = new JSONObject();
			item.put("name", d.getName());
			item.put("value", d.getValue());
			item.put("unit", d.getUnit());
			data.add(item);
		}
		jo.put("details", data);
		return jo;
	}
	
	@Override
	public String toString(){
		return toJSON().toString();
	}

	public boolean isSuccess() {
		return success;
	}

	public List<ResponseItem> getItems() {
		return items;
	}
	
}
